import decimal
from django.db.models import Q
from django.http import StreamingHttpResponse
import os
from xm.settings import BASE_DIR

from django.shortcuts import render, HttpResponse, redirect, reverse
from django.core.paginator import Paginator
from app.models import Book

def search(request, page=1):
    book = Book.objects.all()
    q = Q()
    name = request.GET.get("name")
    if name:
        q = Q(name__contains=name)
    book = Book.objects.filter(q)
    paginator = Paginator(book, 3)
    pager = paginator.get_page(page)
    return render(request, "search.html", locals())

def showbook(request, page=1):
    book = Book.objects.all()
    paginator = Paginator(book, 3)
    pager = paginator.get_page(page)
    return render(request, "book.html", locals())


def delbook(request, bookid):
    Book.objects.get(id=bookid).delete()
    return redirect(reverse('app1:showbook'))


def addbook(request):
    if request.method == "POST":
        name = request.POST.get("name", "")
        price = request.POST.get("price", "")
        isbn_no = request.POST.get("isbn_no", "")
        enterperson = request.POST.get("enterperson", "")
        book = Book(name=name, price=decimal.Decimal(float(price)), isbn_no=isbn_no, enterperson=enterperson)
        book.save()
        return redirect(reverse('app1:showbook'))
    return render(request, "addbook.html")


def editbooks(request, bookid):
    if request.method == 'POST':
        name = request.POST.get("name")
        price = request.POST.get("price")
        isbn_no = request.POST.get("isbn_no")
        Book.objects.filter(id=bookid).update(name=name, price=price, isbn_no=isbn_no)
        return redirect(reverse('app1:showbook'))
    book = Book.objects.get(id=bookid)
    return render(request, "editbook.html", {'book': book})

def upfile(request):
    if request.method=="GET":
        return render(request,"upfile.html")

    if request.method=="POST":
        myfileobj=request.FILES.get("myfile")
        print(type(myfileobj))

        f=open(os.path.join(BASE_DIR,"static",'pic',myfileobj.name),'wb')
        for chunk in myfileobj.chunks():
            f.write(chunk)
        f.close()
        return render(request,"upfile.html")

def download(request,filename):
    file=open(os.path.join(BASE_DIR,'static','pic',filename),'rb')
    response=StreamingHttpResponse(file)
    response['Content-Type']='application/octet-stream'
    response['Content-Disposition']='attachent;filename="{}“'.format(filename)
    return response
